package yang.yu.sunny.eventhandler;

import com.google.common.eventbus.Subscribe;
import org.dayatang.domain.InstanceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yang.yu.sunny.domain.product.Product;
import yang.yu.sunny.domain.product.ProductCategory;
import yang.yu.sunny.domain.product.ProductCategoryNameChangedEvent;
import yang.yu.sunny.domain.product.ProductNameChangedEvent;
import yang.yu.sunny.domain.sales.Customer;
import yang.yu.sunny.domain.sales.CustomerNameChangedEvent;
import yang.yu.sunny.infra.elasticsearch.CustomerSearcher;
import yang.yu.sunny.infra.elasticsearch.ProductCategorySearcher;
import yang.yu.sunny.infra.elasticsearch.ProductSearcher;

/**
 * Created by yyang on 16/3/24.
 */
public class ElasticSearchEventHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchEventHandler.class);

    /**
     * 当数据库中的产品改名时,修改ElasticSearch中的索引
     * @param event
     */
    @Subscribe
    public void productCategoryNameChanged(ProductCategoryNameChangedEvent event) {
        ProductCategorySearcher searcher = InstanceFactory.getInstance(ProductCategorySearcher.class);
        ProductCategory category = searcher.get(event.getProductCategoryId());
        category.setName(event.getNewName());
        searcher.update(category);
        LOGGER.info("Product category name in ES index updated!");
    }

    /**
     * 当数据库中的产品类别改名时,修改ElasticSearch中的索引
     * @param event
     */
    @Subscribe
    public void productNameChanged(ProductNameChangedEvent event) {
        ProductSearcher searcher = InstanceFactory.getInstance(ProductSearcher.class);
        Product category = searcher.get(event.getProductId());
        category.setName(event.getNewName());
        searcher.update(category);
        LOGGER.info("Product name in ES index updated!");
    }

    /**
     * 当数据库中的顾客改名时,修改ElasticSearch中的索引
     * @param event
     */
    @Subscribe
    public void customerNameChanged(CustomerNameChangedEvent event) {
        CustomerSearcher searcher = InstanceFactory.getInstance(CustomerSearcher.class);
        Customer customer = searcher.get(event.getCustomerId());
        customer.setName(event.getNewName());
        searcher.update(customer);
        LOGGER.info("Customer name in ES index updated!");
    }
}
